const express = require('express');
const router = express.Router();
const utils = require("../utils/index.js");
const {primary} = require("../utils/roleString");
const pools = require("../utils/pools.js");
const xlsx = require('node-xlsx');

// 获取客户列表
router.post('/list', async (req, res) => {
    try {
        const { name, contact_info } = req.body;
        let sql = 'SELECT * FROM customer WHERE 1=1';
        const params = [];
        if (name) {
            sql += ' AND name LIKE ' + '"%'+name+'%"';
            // params.push(`%${name}%`);
        }
        if (contact_info) {
            sql += ' AND contact_info LIKE ' + '"%'+contact_info+'%"';
            // params.push(`%${contact_info}%`);
        }
       await pools({sql, val:params,res,req,run:false});
    } catch (error) {
        console.error('获取客户列表失败:', error);
        res.json(utils.error('获取客户列表失败'));
    }
});

// 添加客户
router.post('/add', async (req, res) => {
    try {
        const { name, contact_info, purchase_intent, type } = req.body;

        if (!name) {
            return res.json(utils.error('客户姓名不能为空'));
        }

        const sql = 'INSERT INTO customer (name, contact_info, purchase_intent, type) VALUES (?, ?, ?, ?)';
        await pools({sql, val:[name, contact_info, purchase_intent, type],run:false,res,req});

    } catch (error) {
        console.error('添加客户失败:', error);
        res.json(utils.error('添加客户失败'));
    }
});

// 更新客户信息
router.post('/update', async (req, res) => {
    try {
        const { id,name, contact_info, purchase_intent, type } = req.body;

        if (!name) {
            return res.json(utils.error('客户姓名不能为空'));
        }

        const sql = 'UPDATE customer SET name=?, contact_info=?, purchase_intent=?, type=? WHERE id=?';
        await pools({sql, val:[name, contact_info, purchase_intent, type, id],run:false,res,req});
    } catch (error) {
        console.error('更新客户信息失败:', error);
        res.json(utils.error('更新客户信息失败'));
    }
});

// 删除客户
router.post('/delete', async (req, res) => {
    try {
        const {id} = req.body;
        const sql = 'DELETE FROM customer WHERE id = ?';
        await pools({sql, val:[id],run:false,res,req});
    } catch (error) {
        console.error('删除客户失败:', error);
        res.json(utils.error('删除客户失败'));
    }
});

//导出数据
router.post("/export",async (req,res)=>{
    const { name, contact_info } = req.body;
    let sql = 'SELECT name,contact_info,purchase_intent,type,create_time FROM customer';
    let {result} = await pools({sql,res,req});
    console.log(result)
    let data =[ ['客户姓名','联系方式','购车意向','客户分类','创建时间']];
    result.map(t=>{
        data.push(Object.values(t))
    })
    let buffer = xlsx.build([{name:'sheet1',data}]);
    const filename = '客户数据.xlsx';
    const encodedFilename = encodeURI(filename);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;filename='+encodedFilename);
    res.send(buffer);
});

module.exports = router;
